"""
百度OCR客户端 - 调用百度OCR API进行身份证识别
"""

# 导入requests库，用于发送HTTP请求
import requests

# 导入json库，用于处理JSON数据
import json


class Baidu():
    """
    百度OCR客户端类
    用于调用百度OCR服务进行身份证识别
    """
    
    def __init__(self):
        """
        初始化百度OCR客户端
        设置API密钥，这些密钥需要在百度云控制台申请
        """
        # 百度OCR API Key
        self.API_KEY = "kV4gHPR05PXXG2Sb5FwgC1jd"
        
        # 百度OCR Secret Key
        self.SECRET_KEY = "jw0OGrH8bIVlPcDN0bF6xG9yGS0znO0S"
    
    def idcardfront(self, url_img):
        """
        识别身份证正面
        
        参数:
            url_img: 身份证正面图片的URL地址
            
        返回:
            百度OCR识别结果的JSON对象
        """
        # 构造获取access_token的URL
        url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"%(self.API_KEY,self.SECRET_KEY)
        
        # 发送POST请求获取access_token
        payload = ""
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        
        response = requests.request("POST", url, headers=headers, data=payload)
        
        # 从响应中提取access_token
        access_token = response.json().get("access_token")
        
        # 构造身份证正面识别的URL
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + access_token

        # 构造请求参数
        payload = 'id_card_side=front&url=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false&detect_screenshot=false'%(url_img)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        # 发送POST请求进行身份证正面识别
        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

        # 打印响应文本（用于调试）
        print(response.text)
        
        # 返回JSON格式的识别结果
        return json.loads(response.text)
    
    def idcardback(self, url_img):
        """
        识别身份证反面
        
        参数:
            url_img: 身份证反面图片的URL地址
            
        返回:
            百度OCR识别结果的JSON对象
        """
        # 构造身份证反面识别的URL
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()

        # 构造请求参数
        payload = 'id_card_side=back&url=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false&detect_screenshot=false'%(url_img)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        # 发送POST请求进行身份证反面识别
        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

        # 打印响应文本（用于调试）
        print(response.text)
        
        # 返回JSON格式的识别结果
        return json.loads(response.text)

    def get_access_token(self):
        """
        获取百度OCR的access_token
        
        返回:
            access_token字符串
        """
        # 构造获取access_token的URL
        url = "https://aip.baidubce.com/oauth/2.0/token"
        
        # 构造请求参数
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        
        # 发送POST请求并返回access_token
        return str(requests.post(url, params=params).json().get("access_token"))


# 创建百度OCR客户端实例
idcard = Baidu()